import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Not } from 'typeorm';

import { Permission } from '../entity/permission.entity';

export interface PermissionTree extends Permission {
    children?: PermissionTree[];
}

@Provide()
export class PermissionService {
    @InjectEntityModel(Permission)
    permissionModel: Repository<Permission>;

    /**
     * 创建权限
     */
    async create(permission: Partial<Permission>): Promise<Permission> {
        // 检查权限名称是否存在
        const existPerm = await this.permissionModel.findOne({
            where: { permName: permission.permName }
        });
        if (existPerm) {
            throw new Error('权限名称已存在');
        }

        // 检查权限标识是否存在
        const existPermKey = await this.permissionModel.findOne({
            where: { permCode: permission.permCode }
        });
        if (existPermKey) {
            throw new Error('权限标识已存在');
        }

        // 如果指定了父权限ID，检查父权限是否存在
        if (permission.parentId) {
            const parentPerm = await this.permissionModel.findOne({
                where: { id: permission.parentId, delFlag: 0 }
            });
            if (!parentPerm) {
                throw new Error('父权限不存在');
            }
        }

        const newPermission = this.permissionModel.create(permission);
        return await this.permissionModel.save(newPermission);
    }

    /**
     * 更新权限
     */
    async update(id: number, permission: Partial<Permission>): Promise<boolean> {
        if (permission.permName) {
            const existPerm = await this.permissionModel.findOne({
                where: { permName: permission.permName, id: Not(id) }
            });
            if (existPerm) {
                throw new Error('权限名称已存在');
            }
        }

        if (permission.permCode) {
            const existPermKey = await this.permissionModel.findOne({
                where: { permCode: permission.permCode, id: Not(id) }
            });
            if (existPermKey) {
                throw new Error('权限标识已存在');
            }
        }

        const result = await this.permissionModel.update(id, permission);
        return result.affected > 0;
    }

    /**
     * 删除权限（软删除）
     */
    async delete(id: number): Promise<boolean> {
        const result = await this.permissionModel.update(id, {
            delFlag: 1,
            updateTime: new Date()
        });
        return result.affected > 0;
    }

    /**
     * 获取权限信息
     */
    async getInfo(id: number): Promise<Permission> {
        return await this.permissionModel.findOne({
            where: { id, delFlag: 0 }
        });
    }

    /**
     * 获取权限列表
     */
    async getList(params: {
        page?: number;
        pageSize?: number;
        permName?: string;
        permCode?: string;
        status?: number;
        parentId?: number;
    }): Promise<[Permission[], number]> {
        const { page = 1, pageSize = 10, permName, permCode, status, parentId } = params;

        const queryBuilder = this.permissionModel.createQueryBuilder('permission')
            .where('permission.delFlag = :delFlag', { delFlag: 0 });

        if (permName) {
            queryBuilder.andWhere('permission.permName LIKE :permName', {
                permName: `%${permName}%`
            });
        }

        if (permCode) {
            queryBuilder.andWhere('permission.permCode LIKE :permCode', {
                permCode: `%${permCode}%`
            });
        }

        if (status !== undefined) {
            queryBuilder.andWhere('permission.status = :status', { status });
        }
        
        if (parentId !== undefined) {
            queryBuilder.andWhere('permission.parentId = :parentId', { parentId });
        }

        queryBuilder.orderBy('permission.permSort', 'ASC');

        const skip = (page - 1) * pageSize;
        queryBuilder.skip(skip).take(pageSize);

        return await queryBuilder.getManyAndCount();
    }
    
    /**
     * 获取权限树
     */
    async getPermissionTree(): Promise<PermissionTree[]> {
        // 获取所有未删除的权限
        const permissions = await this.permissionModel.find({
            where: { delFlag: 0 },
            order: { permSort: 'ASC' }
        });
        
        // 构建树结构
        return this.buildPermissionTree(permissions);
    }
    
    /**
     * 构建权限树
     */
    private buildPermissionTree(permissions: Permission[], parentId: number = 0): PermissionTree[] {
        const tree: PermissionTree[] = [];
        
        permissions.forEach(permission => {
            if (permission.parentId === parentId) {
                const node: PermissionTree = { ...permission };
                const children = this.buildPermissionTree(permissions, permission.id);
                
                if (children.length > 0) {
                    node.children = children;
                }
                
                tree.push(node);
            }
        });
        
        return tree;
    }
    
    /**
     * 获取子权限
     */
    async getChildrenByParentId(parentId: number): Promise<Permission[]> {
        return await this.permissionModel.find({
            where: { parentId, delFlag: 0 },
            order: { permSort: 'ASC' }
        });
    }
}